package ro.ubbcluj.adm.twitter.client;

import java.io.IOException;
import java.net.URL;

import sample.twitter.client.R;
import twitter4j.Paging;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class TwitterApp extends Activity {

	private TwitterConnector connector;
	private Twitter twitter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		final EditText editText = ((EditText) findViewById(R.id.textStatus));
		editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					String text = editText.getHint().toString();
					if (text.equals(getString(R.string.hintStatus))) {
						editText.setHint("");
					}
				} else {
					String text = editText.getHint().toString();
					if (text.equals("")) {
						editText.setHint(R.string.hintStatus);
					}
				}
			}
		});

		connector = new TwitterConnector(this);
		connector.setListener(new TwitterConnectorListener() {

			@Override
			public void onConnectionSuccessful(Twitter twitterConnection) {
				twitter = twitterConnection;
				try {
					((TextView) findViewById(R.id.loggedIn)).setText("Logged in as ");
					((TextView) findViewById(R.id.loggedUser)).setText(twitterConnection.getScreenName());
				} catch (IllegalStateException e) {
					Toast.makeText(TwitterApp.this, e.getMessage(), Toast.LENGTH_SHORT).show();
				} catch (TwitterException e) {
					Toast.makeText(TwitterApp.this, e.getMessage(), Toast.LENGTH_SHORT).show();
				}
				updateTimeline();
			}

			@Override
			public void onConnectionAborted() {
				Toast.makeText(TwitterApp.this, R.string.pinCodeRequired, Toast.LENGTH_LONG).show();
				TwitterApp.this.finish();
			}

			@Override
			public void onException(TwitterException exception) {
				Toast.makeText(TwitterApp.this, exception.getMessage(), Toast.LENGTH_LONG).show();
			}

		});
		connector.openTwitterConnection();
	}

	@Override
	public void onStart() {
		super.onStart();
	}

	/**
	 * 
	 * @param view
	 */
	public void onTweetButtonClick(View view) {
		EditText editText = (EditText) findViewById(R.id.textStatus);
		final String text = editText.getText().toString();
		if (twitter != null) {
			new AsyncTask<Void, Void, Integer>() {
				@Override
				protected Integer doInBackground(Void... params) {
					int ok = 0;
					try {
						twitter.updateStatus(text);
						ok = 1;
					} catch (TwitterException e) {
						Toast.makeText(TwitterApp.this, e.getMessage(), Toast.LENGTH_SHORT).show();
					}
					return ok;
				}

				@Override
				protected void onProgressUpdate(Void... params) {
				}

				@Override
				protected void onPostExecute(Integer result) {
					if (result == 1)
						Toast.makeText(TwitterApp.this, R.string.tweetSuccess, Toast.LENGTH_SHORT).show();
				}
			}.execute();
		} else {
			Toast.makeText(this, R.string.connectionNotEstablished, Toast.LENGTH_LONG).show();
		}
		editText.setText("");
	}

	
	public void updateTimeline() {
		if (twitter != null) {
			Toast.makeText(TwitterApp.this, getString(R.string.timelineLoading), Toast.LENGTH_LONG).show();

			new AsyncTask<Void, Void, ResponseList<Status>>() {

				@Override
				protected ResponseList<twitter4j.Status> doInBackground(Void... params) {
					ResponseList<twitter4j.Status> responseList = null;
					try {
						responseList = twitter.getHomeTimeline(new Paging(1, 10));
					} catch (TwitterException e) {
						Toast.makeText(TwitterApp.this, e.getMessage(), Toast.LENGTH_LONG).show();
					}
					return responseList;
				}

				@Override
				protected void onProgressUpdate(Void... params) {
					Toast.makeText(TwitterApp.this, getString(R.string.timelineLoading), Toast.LENGTH_LONG).show();
				}

				@Override
				protected void onPostExecute(ResponseList<twitter4j.Status> responseList) {
					ListView listView = (ListView) findViewById(R.id.timelineList);
					IconicAdapter adapter = new IconicAdapter();
					listView.setAdapter(adapter);
					for (twitter4j.Status status : responseList) {
						adapter.add(new RowModel(status.getUser().getName(), status.getUser().getProfileImageURL(),
								status.getText()));
					}
					Toast.makeText(TwitterApp.this, getString(R.string.timelineSuccess), Toast.LENGTH_SHORT).show();
				}

			}.execute();
		} else {
			Toast.makeText(TwitterApp.this, R.string.connectionNotEstablished, Toast.LENGTH_LONG).show();
		}
	}

	public void onTimelineButtonClick(View view) {
		updateTimeline();

	}

	public void onLogOutClick(View view) {
		PreferencesStorage.deleteAccessTokenToPreferences(this);
		this.finish();
	}

	// -------------------- Iconic Adapter ---------------------

	public class IconicAdapter extends ArrayAdapter<RowModel> {

		public IconicAdapter() {
			super(TwitterApp.this, R.layout.list_item_icon, R.id.tweetLabel);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View row = super.getView(position, convertView, parent);
			RowModel model = this.getItem(position);
			ImageView icon = (ImageView) row.findViewById(R.id.icon);
			Bitmap iconBitmap;
			try {
				iconBitmap = BitmapFactory.decodeStream(model.getImageUrl().openConnection().getInputStream());
				icon.setImageBitmap(iconBitmap);
			} catch (IOException e) {
				Toast.makeText(TwitterApp.this.getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT);
			}
			TextView userTextView = (TextView) row.findViewById(R.id.userLabel);
			userTextView.setText(model.getUser());
			TextView tweetTextView = (TextView) row.findViewById(R.id.tweetLabel);
			tweetTextView.setText(model.getMessage());
			return row;
		}

		@Override
		public void add(RowModel object) {
			super.add(object);
		}

	}

	// --------- RowModel --------------

	public class RowModel {

		private String user;
		private URL imageUrl;
		private String message;

		public RowModel(String user, URL imageUrl, String message) {
			super();
			this.user = user;
			this.imageUrl = imageUrl;
			this.message = message;
		}

		public String getUser() {
			return user;
		}

		public void setUser(String user) {
			this.user = user;
		}

		public URL getImageUrl() {
			return imageUrl;
		}

		public void setImageUrl(URL imageUrl) {
			this.imageUrl = imageUrl;
		}

		public String getMessage() {
			return message;
		}

		public void setMessage(String message) {
			this.message = message;
		}

	}

}
